// Learn cc.Class:
//  - https://docs.cocos.com/creator/manual/en/scripting/class.html
// Learn Attribute:
//  - https://docs.cocos.com/creator/manual/en/scripting/reference/attributes.html
// Learn life-cycle callbacks:
//  - https://docs.cocos.com/creator/manual/en/scripting/life-cycle-callbacks.html


const roleMap = {
    1: {
        name: "勇者", 
        url: "role/hero"
    },
    2: {
        name: "骷髅王", 
        url: "role/npc"
    },
}

cc.Class({
    extends: cc.Component,

    properties: {
        picSprite: cc.Sprite,  //头像
        nameLabel: cc.Label,  //名字文字
        textLabel: cc.Label,   //对话文字
    },

    // LIFE-CYCLE CALLBACKS:

    onLoad () {
       
        



        //将当前dialog 对象暴露全局
        window.dialog = this;

        cc.systemEvent.on("keydown", this.onKeyDown, this);


    },


    onKeyDown(e){
        switch(e.keyCode){
            case cc.macro.KEY.space: {
                this.nextTextData();
                break;
            }
        }
    },

    init(textDataArr){
        this.textIndex = -1;  //对话的下表
        this.nowText = null;   //当前对话的文本
        this.textEnd = true;  //当前对话是否结束
        this.tt = 0 ; //当前播放对话的总时长

        this.textDataArr = textDataArr;
        this.node.active = true;  //当前对象激活（可见）
        this.nextTextData();  //开启下一句对话
    },

    //下一句对话
    nextTextData(){
        if(++this.textIndex < this.textDataArr.length ){  //判断是否还有对话
            this.setTextData(this.textDataArr[this.textIndex]);
        }else{
            this.closeDialog();
        }
    },

    setTextData(textData){
        if(!this.textEnd) return ;
        this.textEnd = false;

        this.nameLabel.string = roleMap[textData.roleId].name;
        this.textLabel.string = "";  //默认刚开始对话为空
        this.nowText = textData.content;  //获取对话内容给nowText

        cc.loader.loadRes(roleMap[textData.roleId].url, cc.SpriteFrame, (err, textTure)=>{
            if(err) {
                console.log(err);
                return false;e
            }
            this.picSprite.spriteFrame = textTure;
        });
    },

    closeDialog(){
        this.node.active = false; //对话结束
    },

    start () {

    },

    update (dt) {
        if(!this.nowText) return;
        this.tt += dt;
        if(this.tt >= 0.1){
            if(this.textLabel.string.length < this.nowText.length){
                this.textLabel.string = this.nowText.slice(0, this.textLabel.string.length+1);
                this.textEnd = false; 
            }else{
                this.textEnd = true;
                this.nowText = null;
            }
            
            this.tt = 0;  //要重置下时间
        }
        
    },
});
